package hn.cch.reactive.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import hn.cch.reactive.entity.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.cache.CacheMono;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Signal;

import java.util.Objects;

@RequestMapping("mono")
@RestController
public class MonoController {

    private static final Logger logger = LoggerFactory.getLogger(MonoController.class);


    @Autowired
    private Cache<String, Message> messageCache;

    @GetMapping("just")
    public Mono<Message> just(@RequestParam(value = "key") String key) {
        Message message = Message.success();
        message.setData(key);
        return Mono.just(message);
    }


    @GetMapping("testCacheMono")
    public Mono<Message> testCacheMono(@RequestParam(value = "key") String key) {
        Message message = Message.success();
        message.setData(key);
        logger.info("testCacheMono key:{}", key);
        messageCache.put(key, message);
        Mono<Message> result = CacheMono
            .lookup(k -> Mono.justOrEmpty(messageCache.getIfPresent(k)).map(Signal::next), key)
            .onCacheMissResume(Mono.just(message))
            .andWriteWith((k, signal) -> Mono.fromRunnable(() ->
                messageCache.put(k, Objects.requireNonNull(signal.get()))
            ));

        return result;
    }
}
